package xyz.hubery.controller;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.hubery.model.BaseResult;
import xyz.hubery.pojo.CartGoods;
import xyz.hubery.pojo.Orders;
import xyz.hubery.service.CartService;
import xyz.hubery.service.OrdersService;

import java.util.List;

@RestController
@RequestMapping("/user/orders")
public class OrdersController {
    @DubboReference
    private OrdersService ordersService;
    @DubboReference
    private CartService cartService;

    @PostMapping("/add")
    public BaseResult<Orders> add(@RequestBody Orders orders, @RequestHeader Long userId) {
        // 保存订单
        orders.setUserId(userId);
        Orders add = ordersService.add(orders);
        // 删除缓存中的购物车数据
        List<CartGoods> cartGoods = orders.getCartGoods();
        for (CartGoods cartGood : cartGoods) {
            cartService.deleteCartOption(userId, cartGood.getGoodId());
        }
        return BaseResult.ok(add);
    }


    /**
     * 根据id查询订单
     *
     * @param id 订单id
     * @return 查询结果
     */
    @GetMapping("/findById")
    public BaseResult<Orders> findById(String id) {
        Orders orders = ordersService.findById(id);
        return BaseResult.ok(orders);
    }

    /**
     * 查询用户的订单
     *
     * @param status 订单状态：1.未付款 2.已付款 3.未发货 4.已发货 5.交易成功 6.交易关闭 7.待评价，传入空值代表查询所有
     * @param userId 用户id
     * @return 查询结果
     */
    @GetMapping("/findUserOrders")
    public BaseResult<List<Orders>> findUserOrders(Integer status, @RequestHeader Long userId) {
        List<Orders> orders = ordersService.findUserOrders(userId, status);
        return BaseResult.ok(orders);
    }

}
